<template>
  <div class="app-container">
    <el-row>
      <el-col :span="12">

        <el-row>
          <el-col :span="1.5">
            <el-button
                type="primary"
                icon="Plus"
                size="small"
                @click="handleAdd"
                v-hasPermi="['system:dict:add']"
            >新增
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
                type="success"
                icon="Edit"
                size="small"
                :disabled="single"
                @click="handleUpdate"
                v-hasPermi="['system:dict:edit']"
            >修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
                type="danger"
                icon="Delete"
                size="small"
                :disabled="single"
                @click="handleDelete"
                v-hasPermi="['system:dict:remove']"
            >删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
                type="warning"
                size="small"
                :disabled="single"
                @click="handleAddUser"
                v-hasPermi="['system:dict:add']"
            >移动用户
            </el-button>
          </el-col>

          <el-col :offset="7" :span="6">
            <el-form-item label="用户组">
              <el-input
                  v-model="queryGroupParams.groupNameCon"
                  placeholder="请输入用户组"
                  clearable
                  size="small"
                  :style="{width: '100%'}"
                  @keyup.enter="handleGroupQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="1.5">
            <el-form-item>
              <el-button type="primary" icon="Search" size="small" @click="handleGroupQuery">搜索</el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <xTable ref="refGroupTable" refId="refGroupTable" multiple="false" v-loading="loading"
                  @selection-change="handleGroupSelectionChange"
                  :data="groupList" >
          <template #columList>
          <el-table-column label="序号" type="index" width="55"/>
          <el-table-column label="组合编号" align="center" prop="groupId" v-if="false"></el-table-column>
          <el-table-column label="组合名称" align="left" prop="groupName" v-if="true"
                           :show-overflow-tooltip="true"></el-table-column>
          <el-table-column label="顺序" align="center" prop="groupSort" v-if="false"></el-table-column>
          <el-table-column label="状态" align="center" prop="status" :show-overflow-tooltip="true"
                           v-if="false"></el-table-column>
          <el-table-column label="备注" align="left" prop="remark" :show-overflow-tooltip="true"
                           v-if="true"></el-table-column>
          </template>
        </xTable>
        <pagination
            v-show="groupTotal>0"
            :total="groupTotal"
            v-model:page="queryGroupParams.pageNum"
            v-model:limit="queryGroupParams.pageSize"
            style="float:right"
            @pagination="getGroupList"
        />

      </el-col>
      <el-col :span="0.5">
        <el-divider direction="vertical" content-position="center"></el-divider>
      </el-col>
      <el-col :span="11">
        <el-row>
          <el-col v-if="false" :span="1.5">
            <el-button
                type="warning"
                size="small"
                :disabled="single"
                @click="handleAddUser"
                v-hasPermi="['system:dict:add']"
            >移动用户
            </el-button>
          </el-col>

          <el-col :offset="12" :span="6">
            <el-form-item label="用户">
              <el-input
                  v-model="queryInUserParams.userNameCon"
                  placeholder="请输入用户"
                  clearable
                  size="small"
                  style="width: 240px"
                  @keyup.enter="handleInUserQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="1.5">
            <el-form-item>
              <el-button type="primary" icon="Search" size="small" @click="handleInUserQuery">搜索</el-button>
            </el-form-item>
          </el-col>
        </el-row>


        <xTable ref="refUserTable" refId="refUserTable" multiple="false" v-loading="loading"  :data="inUserList">
          <template #columList>
          <el-table-column label="序号" type="index" width="55"/>
          <el-table-column v-if="false" align="center" label="用户ID" prop="userId"/>
          <el-table-column label="用户名" align="center" prop="userName"/>
          <el-table-column label="状态" align="center" prop="status">
            <template #default="scope">
              <dict-tag :options="userStatus" :value="scope.row.status"/>
            </template>
          </el-table-column>
          <el-table-column label="邮箱" align="left" width="150" prop="email"/>
          <el-table-column label="手机" align="center" prop="mobileNum"/>
          </template>
        </xTable>
        <pagination
            v-show="inUserTotal > 0"
            :total="inUserTotal"
            v-model:page="queryInUserParams.pageNum"
            v-model:limit="queryInUserParams.pageSize"
            style="float:right"
            @pagination="getInUserListByGroupId"
        />

      </el-col>
    </el-row>
    <!-- 添加或修改 用户组 对话框 -->
    <el-dialog :title="groupTitle" v-model="groupOpen" width="400px" :close-on-click-modal="false" draggable
               destroy-on-close append-to-body>
      <el-form ref="groupRef" :model="groupForm" :rules="groupRules" label-width="80px">
        <el-form-item label="组合名称" prop="groupName">
          <el-input v-model="groupForm.groupName" maxlength="15" placeholder="请输入用户组名称"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="groupForm.remark" type="textarea" rows="3" maxlength="100" show-word-limit placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>

    </el-dialog>
    <!-- 用户组 添加或者删除 用户 对话框 -->
    <el-dialog :title="groupTransferTitle" v-model="groupTransferOpen" width="880px" append-to-body>

      <div style="text-align: center">
        <el-row :gutter="10" style="display:block;margin:0 auto">
          <el-transfer
              style="text-align: left; display: inline-block;width:850px"
              filterable
              :titles="['未选择用户', '已选择用户']"
              :button-texts="['到左边', '到右边']"
              @change="handleChange"
              v-model="inUserListTransfer"
              :props="transferProps"
              :data="outUserListTransfer">
          </el-transfer>
        </el-row>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitTransferForm">确 定</el-button>
          <el-button @click="cancelTransfer">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="UserGroup">
import {ref} from "vue";
import {
  addPricUserGroup,
  dealTransferUser,
  deletePricUserGroup,
  findInUserList,
  findOutUserList,
  findUserList,
  getPricUserGroupById,
  getPricUserGroupList,
  updatePricUserGroup
} from "../../../api/pricingconfig/usergroup";

const {proxy} = getCurrentInstance();
const {M_TYPE, A_TYPE, CURRENCY, userStatus} = proxy.useDict("M_TYPE", "A_TYPE", "CURRENCY", "userStatus");

// 用户组列表
const groupList = ref([]);
// 用户组内用户列表
const inUserList = ref([]);
const outUserList = ref([]);
const inUserListTransfer = ref([]);
const outUserListTransfer = ref([]);
const groupOpen = ref(false);
const groupTransferOpen = ref(false);

const selectionGroupRow = ref([]);
const groupTitle = ref('');
const groupTransferTitle = ref('');

const loading = ref(true);
const showSearch = ref(true);
//
const ids = ref([]);
//索引
const indexs = ref([]);
const rows = ref([]);

const single = ref(true);
const multiple = ref(true);
const groupTotal = ref(0);
const inUserTotal = ref(0);
const outUserTotal = ref(0);
const dateRange = ref([]);

const data = reactive({
  groupForm: {
    groupName: null,
    remark: null
  },
  queryGroupParams: {
    pageNum: 1,
    pageSize: 20,
    groupNameCon: undefined
  },
  groupRules: {
    groupName: [{required: true, message: "用户组名称不能为空", trigger: "blur"}]
  },
  queryInUserParams: {
    pageNum: 1,
    pageSize: 20,
    userNameCon: undefined,
    groupId: undefined
  },
  queryOutUserParams: {
    pageNum: 1,
    pageSize: 20,
    userName: undefined,
    groupId: undefined
  },
  // Transfer数据源的字段别名
  transferProps: {
    key: 'userId',
    label: 'userName'
  },
});
const {
  queryInUserParams,
  queryOutUserParams,
  queryGroupParams,
  groupForm,
  groupRules,
  transferProps
} = toRefs(data);


/** 查询用户组列表 */
function getGroupList() {
  loading.value = true;
  getPricUserGroupList(queryGroupParams.value).then(response => {
    groupList.value = response.list;
    groupTotal.value = response.total;
    loading.value = false;
  });
}

/** 根据用户组 查询用户列表 */
function getInUserListByGroupId() {
  loading.value = true;
  findInUserList(queryInUserParams.value).then(response => {
    inUserList.value = response.list;
    inUserTotal.value = response.total;
    loading.value = false;
  });
}

/** 根据用户组 查询用户列表 */
function getInUserList() {
  loading.value = true;
  findInUserList(queryInUserParams.value).then(response => {
    for (let i = 0; i < response.list.length; i++) {
      for (let i = 0; i < response.list.length; i++) {
        inUserListTransfer.value[i] = response.list[i].userId;
      }
    }
    loading.value = false;
  });
}


/** 根据用户组 查询用户列表 */
function getOutUserList() {
  loading.value = true;
  findOutUserList(queryOutUserParams.value).then(response => {
    outUserList.value = response.list;
    outUserTotal.total = response.total;
    outUserListTransfer.value = outUserList.value;
    loading.value = false;
  });
}

/** 根据用户组 查询用户列表 */
function getUserList() {
  loading.value = true;
  findUserList().then(response => {
    outUserList.value = response.list;
    outUserTotal.total = response.total;
    outUserListTransfer.value = outUserList.value;
    loading.value = false;
  });
}

/** 多选框选中数据 */
function handleGroupSelectionChange(selection, v1, v2, v3) {

  if (selection.length > 0) {
    ids.value = selection.map(item => item.groupId);
    indexs.value = selection.map(item => item.index);
    rows.value = selection.map(item => item);
  } else {
    ids.value = [];
    indexs.value = [];
    rows.value = [];
  }
  single.value = selection.length != 1;
  multiple.value = !selection.length;
  if (selection.length == 1) {
    queryInUserParams.value.groupId = ids.value[0];
    getInUserListByGroupId();
  }

  if (selection.length != 1) {
    inUserList.value = [];
    inUserTotal.value = 0;
  }
}

/** 用户组 搜索按钮操作 */
function handleGroupQuery() {
  queryGroupParams.value.pageNum = 1;
  getGroupList();
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  groupOpen.value = true;
  groupTitle.value = "添加用户组";
}

/**  添加用户 按钮操作 */
function handleAddUser(row) {

  outUserListTransfer.value = [];
  inUserListTransfer.value = [];
  const groupIds = row.groupId || ids.value;
  queryOutUserParams.value.groupId = groupIds[0];
  queryInUserParams.value.groupId = groupIds[0];
  getUserList();
  getInUserList();
  groupTransferOpen.value = true;
  groupTransferTitle.value = "移动用户";
}

/** 用户组  修改按钮操作 */
function handleUpdate(row) {
  reset();
  const groupId = row.groupId || ids.value;
  getPricUserGroupById(groupId[0]).then(response => {
    groupForm.value = response.msg;
    groupOpen.value = true;
    groupTitle.value = "修改用户组";
  });
}


/** 用户组  修改/新增   */
function submitForm() {
  proxy.$refs["groupRef"].validate(valid => {
    if (valid) {
      if (groupForm.value.groupId != undefined) {
        updatePricUserGroup(groupForm.value).then(response => {
          if (response.success) {
            proxy.$modal.msgSuccess("修改成功");
            groupOpen.value = false;
            getGroupList();
          } else {
            proxy.$modal.msgError(response.msg);
          }
        });
      } else {
        addPricUserGroup(groupForm.value).then(response => {
          if (response.success) {
            proxy.$modal.msgSuccess("新增成功");
            groupOpen.value = false;
            getGroupList();
          } else {
            proxy.$modal.msgError(response.msg);
          }
        });
      }
    }
  });
}

/** 用户组  增加删除 用户   */
function submitTransferForm() {
  var inUsers = inUserListTransfer.value;
  var outUsers = outUserListTransfer.value;
  var groupId = ids.value[0];
  var param = {"groupId": groupId, "userIds": JSON.stringify(inUsers)};
  dealTransferUser(param).then(response => {
    if (response.success) {
      proxy.$modal.msgSuccess("操作成功");
      groupOpen.value = false;
      getInUserListByGroupId();
      rows.map(item => {
        proxy.$refs.refGroupTable.toggleRowSelection(item, true)
      })
    } else {
      proxy.$modal.msgError(response.msg);
    }
  });
  groupTransferOpen.value = false;
}

/** 删除按钮操作 */
function handleDelete(row) {
  const groupIds = ids.value;
  const groupName = rows.value[0].groupName;
  proxy.$modal.confirm('是否确认删除组合为 "' + groupName + '"的数据项？').then(function () {
    return deletePricUserGroup(groupIds);
  }).then(() => {
    getGroupList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 取消按钮 */
function cancel() {
  groupOpen.value = false;
  reset();
}

/** 取消按钮 */
function cancelTransfer() {
  groupTransferOpen.value = false;

}

/** 表单重置 */
function reset() {
  groupForm.value = {
    groupName: undefined,
    remark: undefined
  };
  proxy.resetForm("groupRef");
}

/** 用户 搜索按钮操作 */
function handleInUserQuery() {
  queryInUserParams.value.pageNum = 1;
  inUserList.value = [];
  inUserTotal.value = 0;
  if (ids.value.length == 1) {
    getInUserListByGroupId();
  }

}


/** 导出按钮操作 */
function handleExport() {
  proxy.download("xxx/export", {
    ...queryParams.value
  }, `xxx信息${new Date().getTime()}.xlsx`);
}

/** 导出按钮操作 */
function handleExportAll() {
  proxy.download("xxx/export", Object.assign({
    ...queryParams.value
  }, {pageSize: ''}), `xxx信息${new Date().getTime()}.xlsx`);
}

function RowClassName({row, rowIndex}) {	//行元素，行索引
  row.index = rowIndex;
}

getGroupList();
</script>
